package com.bit.forum.controller;

import com.bit.forum.common.AppResult;
import com.bit.forum.common.ResultCode;
import com.bit.forum.config.APPConfig;
import com.bit.forum.model.User;
import com.bit.forum.services.IUserService;
import com.bit.forum.services.impl.UserServiceImpl;
import com.bit.forum.utils.MD5Utils;
import com.bit.forum.utils.StringUtils;
import com.bit.forum.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.http.HttpRequest;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("用户昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //1.验证参数的有效性
        if ( StringUtils.isEmpty(username)
                || StringUtils.isEmpty(nickname)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }


        //2.处理密码
        //2.1 校验密码和确认密码是否相等
        if (!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.getMessage());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME.getMessage());
        }

        //2.2 数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        String salt = UUIDUtils.UUID_32();
        String spassword = MD5Utils.md5Salt(password,salt);
        user.setPassword(spassword);
        user.setSalt(salt);

        //3.调用service
        userService.createNormal(user);
        return AppResult.success();
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") String username,
                           @ApiParam("密码") @RequestParam("password") String password){
        //1.调用service中的登录方法,返回User对象
        User user = userService.login(username,password);
        if (user == null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //2.如果登录成功就把User对象设置到Session作用域中
        HttpSession session = request.getSession(true); //没有session时创建一个
        session.setAttribute(APPConfig.USER_SESSION,user);
        //3.返回
        return AppResult.success();
    }


    /**
     * 根据id获取用户信息
     * @param request
     * @param id
     * @return
     */

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        //User对象  //当用户不传信息,从session获取

        User user = null;
        //1.如果id为空从session获取
        if (id == null){
            HttpSession session = request.getSession(false); //没有session.不创建
//            //判断session是否存在
//            if (session == null || session.getAttribute(APPConfig.USER_SESSION )== null){ //用户没有登录
//                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
//            }
            user = (User) session.getAttribute(APPConfig.USER_SESSION);
        }else {
            //2.id不为空,从数据库查询
            user = userService.selectById(id);
        }
        //判断是否为空
        if (user == null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        return AppResult.success(user);
    }

    /**
     * 退出
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //获取session
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if (session != null){
            //表示用户登录状态
            log.info("退出成功"); //用户登录状态下打印的
            session.invalidate();//销毁

        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false)String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false)Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false)String email,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false)String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false)String remark){

        //非空校验
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(email) &&StringUtils.isEmpty(phoneNum)
                &&StringUtils.isEmpty(remark) && gender == null){
            return AppResult.failed("请输入要修改的内容");
        }
        //封装对象
        User updateUser = new User();

        //session获取
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(APPConfig.USER_SESSION);
        updateUser.setId(user.getId());

        updateUser.setUsername(username);
        updateUser.setEmail(email);
        updateUser.setGender(gender);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setNickname(nickname);
        updateUser.setRemark(remark);

        userService.modifyInfo(updateUser);
        //查询最新的用户信息
        user = userService.selectById(user.getId());
        //把最新的值设置到session
        session.setAttribute(APPConfig.USER_SESSION,user);
        return AppResult.success(user);
    }


    @ApiOperation("密码修改")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("旧密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认新密码") @RequestParam("passwordRepeat") @NonNull String  passwordRepeat){
        //校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前的登录信息
        HttpSession session =request.getSession(false);
        User user = (User) session.getAttribute(APPConfig.USER_SESSION);
        //调用service
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //销毁session
        if (session!= null){
            session.invalidate();
        }
        //返回结果
        return AppResult.success();

    }
}
